using System.Collections.Generic;
using System.IO;
using Baula.TextGen.Framework.Tools;

namespace Baula.TextGen.Framework
{
    internal class TemplateParser
    {
        private readonly bool _isParsingDocumentTemplate;
        public Dictionary<string, PartTemplate> PartTemplates { get; private set; }

        public TemplateParser(bool isParsingDocumentTemplate)
        {
            // REFACTOR: Instead of this flag create dedicated derived parsers for parsing DocumentTemplate and PartTemplate
            _isParsingDocumentTemplate = isParsingDocumentTemplate;
        }

        public void Parse(string content)
        {
            PartTemplates = new Dictionary<string, PartTemplate>();
            using(var reader = new StringReader(content))
            {
                var partTemplate = Factory.CreatePartTemplate();

                var line = reader.ReadLine();
                while (line != null)
                {
                    if (PartTemplate.IsBegin(line))
                    {
                        FinishParsingPartTemplate(partTemplate);

                        partTemplate = Factory.CreatePartTemplate(line);
                        PartTemplates.Add(partTemplate.Name, partTemplate);
                    }
                    else
                    {
                        partTemplate.AppendLine(line, IsParsingDocumentTemplate);
                    }

                    line = reader.ReadLine();
                }

                FinishParsingPartTemplate(partTemplate);
            }
        }

        private void FinishParsingPartTemplate(PartTemplate partTemplate)
        {
            if (partTemplate.IsRootPart)
            {
                RootPartTemplate = partTemplate;
            }
            partTemplate.OnReachedLastLine();
        }

        public PartTemplate RootPartTemplate { get; private set; }

        private bool IsParsingDocumentTemplate
        {
            get { return _isParsingDocumentTemplate; }
        }
    }
}